﻿Imports System.Diagnostics
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Public Class Encryption

    '24 byte or 192 bit key and IV for TripleDES
    Private Shared KEY_256() As Byte = {17, 16, 93, 156, 178, 24, 218, 32, _
            15, 167, 244, 8, 26, 25, 155, 12, _
            2, 94, 11, 204, 119, 35, 184, 197, 24, 200, 174, 1, 44, 32, 209, 123}

    Private Shared IV_256() As Byte = {155, 13, 26, 179, 236, 99, 17, 63, _
            42, 59, 162, 83, 184, 70, 209, 130, _
            145, 23, 100, 58, 173, 130, 121, 222, 155, 203, 46, 179, 236, 199, 67, 37}

    'Standard DES encryption
    Public Shared Function Encrypt(ByVal value As String) As String
        If value <> "" Then

            Dim cryptoProvider As New System.Security.Cryptography.RijndaelManaged
            cryptoProvider.BlockSize = 256
            cryptoProvider.KeySize = 256
            Dim ms As MemoryStream = New MemoryStream
            Dim cs As CryptoStream = _
                New CryptoStream(ms, cryptoProvider.CreateEncryptor(KEY_256, IV_256), _
                    CryptoStreamMode.Write)
            Dim sw As StreamWriter = New StreamWriter(cs)

            sw.Write(value)
            sw.Flush()
            cs.FlushFinalBlock()
            ms.Flush()

            'convert back to a string
            Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
        Else : Return ""
        End If
    End Function


    'Standard DES decryption
    Public Shared Function Decrypt(ByVal value As String) As String
        If value <> "" Then

            Dim cryptoProvider As New System.Security.Cryptography.RijndaelManaged
            cryptoProvider.BlockSize = 256
            cryptoProvider.KeySize = 256
            'convert from string to byte array
            Dim buffer As Byte() = Convert.FromBase64String(value)
            Dim ms As MemoryStream = New MemoryStream(buffer)
            Dim cs As CryptoStream = _
                New CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_256, IV_256), _
                    CryptoStreamMode.Read)
            Dim sr As StreamReader = New StreamReader(cs)

            Return sr.ReadToEnd()
        Else : Return ""
        End If
    End Function
End Class
